<template>
  <div>
    <el-breadcrumb separator="/">
      <el-breadcrumb-item :to="{ path: '/home' }">首页</el-breadcrumb-item>
      <el-breadcrumb-item>商品管理</el-breadcrumb-item>
      <el-breadcrumb-item>商品列表</el-breadcrumb-item>
    </el-breadcrumb>

    <el-card class="box-card ">
      <el-alert
        class="el-icon-warning"
        title="只允许第三级分类设置参数"
        type="warning"
        :closable="false"
      >
      </el-alert>

      <el-cascader
        v-model="cascaderValue"
        :options="cascaderList"
        :props="props"
        @change="handleChange"
      ></el-cascader>

      <el-tabs
        v-model="CateParams.attr_sel"
        @tab-click="handleClick(CateParams.attr_sel)"
      >
        <el-tab-pane label="动态参数" name="many">
          <el-button
            type="primary"
            @click="addVisible = true"
            :disabled="ifShowAddButton"
            >添加动态参数</el-button
          >
          <template>
            <el-table :data="manyList" border style="width: 100%">
              <el-table-column type="expand">
                <template slot-scope="scope">
                  <el-tag
                    v-for="(item, index) in scope.row.attr_vals"
                    :key="index"
                    closable
                    @close="handleClose(scope.row, index)"
                    >{{ item }}</el-tag
                  >

                  <el-input
                    class="input-new-tag"
                    v-if="scope.row.inputVisible"
                    v-model="scope.row.inputValue"
                    ref="saveTagInput"
                    size="small"
                    @keyup.enter.native="handleInputConfirm(scope.row)"
                    @blur="handleInputConfirm(scope.row)"
                  >
                  </el-input>
                  <el-button
                    v-else
                    class="button-new-tag"
                    size="small"
                    @click="showInput(scope.row)"
                    >+ New Tag</el-button
                  >
                </template>
              </el-table-column>
              <el-table-column type="index" label="#"> </el-table-column>
              <el-table-column prop="attr_name" label="参数名称" width="180">
              </el-table-column>
              <el-table-column label="操作">
                <template slot-scope="scope">
                  <el-button
                    type="primary"
                    icon="el-icon-edit"
                    @click="editParams(scope.row)"
                  ></el-button>
                  <el-button
                    type="danger"
                    icon="el-icon-delete"
                    @click="deleteParams(scope.row)"
                  ></el-button>
                </template>
              </el-table-column>
            </el-table>
          </template>
        </el-tab-pane>
        <el-tab-pane label="静态属性" name="only">
          <template>
            <el-button
              type="primary"
              @click="addVisible = true"
              :disabled="ifShowAddButton"
              >添加静态属性</el-button
            >
            <el-table :data="onlyList" border style="width: 100%">
              <el-table-column type="expand"> </el-table-column>
              <el-table-column type="index" label="#"> </el-table-column>
              <el-table-column prop="attr_name" label="参数名称" width="180">
              </el-table-column>
              <el-table-column label="操作">
                <template slot-scope="scope">
                  <el-button
                    type="primary"
                    icon="el-icon-edit"
                    @click="editParams(scope.row)"
                  ></el-button>
                  <el-button
                    type="danger"
                    icon="el-icon-delete"
                    @click="deleteParams(scope.row)"
                  ></el-button>
                </template>
              </el-table-column>
            </el-table>
          </template>
        </el-tab-pane>
      </el-tabs>

      <!-- 修改参数弹出框 -->
      <el-dialog :title="text" :visible.sync="dialogVisible" width="50%">
        <el-form ref="editFormRef" :model="editForm" label-width="80px">
          <el-form-item label="新属性值">
            <el-input v-model="editForm.attr_name"></el-input>
          </el-form-item>
        </el-form>
        <span slot="footer" class="dialog-footer">
          <el-button @click="dialogVisible = false">取 消</el-button>
          <el-button type="primary" @click="editAttr_name">确 定</el-button>
        </span>
      </el-dialog>

      <!-- 添加参数弹出框 -->
      <el-dialog
        :title="cascaderText"
        :visible.sync="addVisible"
        width="50%"
        @close="addReset"
      >
        <el-form
          ref="addFormRef"
          :model="addForm"
          :rules="rules"
          label-width="80px"
        >
          <el-form-item :label="addLabel" prop="attr_name">
            <el-input v-model="addForm.attr_name"></el-input>
          </el-form-item>
        </el-form>
        <span slot="footer" class="dialog-footer">
          <el-button @click="addVisible = false">取 消</el-button>
          <el-button type="primary" @click="addAttr_name">确 定</el-button>
        </span>
      </el-dialog>
    </el-card>
  </div>
</template>

<script>
export default {
  data() {
    return {
      inputVisible: false,
      inputValue: "",
      //添加表单验证规则
      rules: {
        attr_name: [{ required: true, message: "请输入数据", trigger: "blur" }],
      },
      //添加表单内的数据
      addForm: {
        attr_name: "",
      },
      CateParams: {
        attr_sel: "many",
        attr_id: 0,
      },
      //是否显示弹出框
      dialogVisible: false,
      addVisible: false,
      text: "修改动态参数",

      //修改表单内的数据
      editForm: {
        attr_id: 0,
        cat_id: 0,
        attr_name: "",
        attr_sel: "many",
        attr_vals: "",
      },
      cascaderValue: [],
      cascaderList: [],
      //动态参数数据
      manyList: [],
      //静态属性数据
      onlyList: [],
      props: {
        label: "cat_name",
        children: "children",
        value: "cat_id",
        expandTrigger: "hover",
      },
    };
  },
  computed: {
    cascaderText() {
      if (this.CateParams.attr_sel == "many") {
        return "动态参数";
      } else {
        return "静态属性";
      }
    },

    addLabel() {
      if (this.CateParams.attr_sel == "many") {
        return "添加参数";
      } else {
        return "添加属性";
      }
    },

    ifShowAddButton() {
      if (this.cascaderValue.length === 0) {
        return true;
      } else {
        return false;
      }
    },
  },
  created() {
    this.getCategories();
  },
  methods: {
    async handleInputConfirm(item) {
      let inputValue = item.inputValue;
      if (inputValue.trim() !== "") {
        item.attr_vals.push(inputValue);
      } else {
        item.inputVisible = false;
        item.inputValue = "";
        return this.$message.error("增加该参数失败");
        
      }

      const { data: res } = await this.$http.put(
        "categories/" + item.cat_id + "/attributes/" + item.attr_id,
        {
          attr_name: item.attr_name,
          attr_sel: item.attr_sel,
          attr_vals: item.attr_vals.join(" "),
        }
      );
      if (res.meta.status !== 200) {
        this.$message.error("增加该参数失败");
      } else {
        this.$message.success("增加该参数成功");
      }

      item.inputVisible = false;
      item.inputValue = "";
    },
    showInput(item) {
      item.inputVisible = true;
      this.$nextTick((_) => {
        this.$refs.saveTagInput.$refs.input.focus();
      });
    },
    //级联选择框切换分类时触发
    async handleChange(newValue) {
      if (newValue.length !== 3) {
        this.manyList = [];
        this.onlyList = [];
        return (this.cascaderValue = []);
      }
      this.CateParams.attr_id = this.cascaderValue[2];
      // console.log(this.CateParams);
      this.getTab();
    },

    //获取级联菜单数据
    async getCategories() {
      const { data: res } = await this.$http.get("categories");
      if (res.meta.status !== 200) {
        this.$message.error("获取级联菜单数据失败");
      } else {
        this.cascaderList = res.data;
        // console.log(res);
      }
    },

    //获取标签页内的数据
    async getTab() {
      const { data: res } = await this.$http.get(
        "categories/" + this.CateParams.attr_id + "/attributes",
        {
          params: {
            sel: this.CateParams.attr_sel,
          },
        }
      );
      if (res.meta.status !== 200) {
        var data;
        data = this.CateParams.attr_sel == "many" ? "动态参数" : "静态属性";
        this.$message.error(`获取${data}失败`);
      } else {
        res.data.forEach((item) => {
          if (item.attr_vals.trim() === "") {
            item.attr_vals = [];
          } else {
            item.attr_vals = item.attr_vals.split(" ");
          }
          item.inputVisible = false
          item.inputValue =''
          console.log(item);
        });
        if (this.CateParams.attr_sel == "many") {
          this.manyList = res.data;
          this.text = "修改动态参数";
        } else {
          this.onlyList = res.data;
          this.text = "修改静态属性";
        }
      }
      // console.log(res);
    },

    // 更改标签页
    handleClick(value) {
      this.getTab();
    },

    //点击编辑按钮，修改动态参数或静态属性数据
    editParams(data) {
      this.editForm.attr_id = data.attr_id;
      this.editForm.cat_id = data.cat_id;
      this.editForm.attr_sel = data.attr_sel;
      this.editForm.attr_vals = data.attr_vals;
      this.editForm.attr_name = data.attr_name;

      this.dialogVisible = true;
      console.log(this.editForm);
    },

    //点击确定，发送请求修改参数名称
    async editAttr_name() {
      console.log(this.editForm.attr_name);

      const { data: res } = await this.$http.put(
        "categories/" +
          this.editForm.cat_id +
          "/attributes/" +
          this.editForm.attr_id,
        this.editForm
      );

      if (res.meta.status !== 200) {
        this.editForm.attr_sel == "many"
          ? this.$message.error("修改动态参数失败")
          : this.$message.error("修改静态属性失败");
      } else {
        this.editForm.attr_sel == "many"
          ? this.$message.success("修改动态参数成功")
          : this.$message.success("修改静态属性成功");
        this.getTab();
      }

      this.dialogVisible = false;
    },

    //点击删除按钮，删除动态参数或静态属性数据
    async deleteParams(data) {
      const flag = await this.$confirm(
        "此操作将永久删除该参数, 是否继续?",
        "提示",
        {
          confirmButtonText: "确定",
          cancelButtonText: "取消",
          type: "warning",
        }
      ).catch((err) => err);

      if (flag !== "confirm") {
        this.$message.info("你取消了删除操作");
      } else {
        var msg = this.CateParams.attr_sel === "many" ? "动态参数" : "静态属性";
        const { data: res } = await this.$http.delete(
          "categories/" + data.cat_id + "/attributes/" + data.attr_id
        );

        if (res.meta.status !== 200) {
          this.$message.error("删除" + msg + "失败");
        } else {
          this.$message.success("删除" + msg + "成功");
          this.getTab();
        }
      }
    },

    //点击确定，增加新参数或者属性
    addAttr_name() {
      this.$refs.addFormRef.validate(async (valid) => {
        if (!valid) return this.$message.error("表单验证失败");

        const { data: res } = await this.$http.post(
          "categories/" + this.CateParams.attr_id + "/attributes",
          {
            attr_name: this.addForm.attr_name,
            attr_sel: this.CateParams.attr_sel,
          }
        );

        if (res.meta.status !== 201) {
          return this.$message.error("添加参数或属性失败");
        }
        this.$message.success("添加参数或属性成功");
        this.getTab();
        this.addVisible = false;
      });
    },

    //取消或确定添加参数后，重置表单
    addReset() {
      this.$refs.addFormRef.resetFields();
    },

    //点击删除参数tag标签
    async handleClose(item, index) {
      item.attr_vals.splice(index, 1);
      const { data: res } = await this.$http.put(
        "categories/" + item.cat_id + "/attributes/" + item.attr_id,
        {
          attr_name: item.attr_name,
          attr_sel: item.attr_sel,
          attr_vals: item.attr_vals.join(" "),
        }
      );
      if (res.meta.status !== 200) {
        this.$message.error("删除该参数失败");
      } else {
        this.$message.success("删除该参数成功");
      }

      console.log(item);
    },
  },
};
</script>

<style scoped>
.el-cascader {
  margin-top: 20px;
}

.el-tag + .el-tag {
  margin-left: 10px;
  
}
.button-new-tag {
  margin-left: 10px;
  height: 32px;
  line-height: 30px;
  padding-top: 0;
  padding-bottom: 0;
}
.input-new-tag {
  width: 90px;
  margin-left: 10px;
  vertical-align: bottom;
}

.el-tag{
  margin-top:10px;
}
</style>
